//
//  YWMaterialNumbleCertainTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/9/20.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWMaterialNumbleCertainTableViewController.h"
#import "YWMaterialRecordTableViewController.h"
#import "YWMaterialDetailAndCertainHeadTableViewCell.h"
#import "YWMaterialInfoTableViewCell.h"

#import "YWMacro.h"
#import "UIImage+Extension.h"
#import "UIColor+CustomColors.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YWCommonTool.h"
#import "YWConst.h"
#import "MBProgressHUD.h"

#import "YWMaterialStockOut.h"
#import "YWMaterialRelation.h"
#import "YWMaterialStockOutDetail.h"
#import "YWMaterialReturn.h"
#import "YWMaterialReturnDetail.h"
#import "YWMaterial.h"
#import "YWMaterialManager.h"
#import "YWMaterialStock.h"

@interface YWMaterialNumbleCertainTableViewController ()
@property (nonatomic, strong) UIView * footView;
@property (nonatomic, strong) NSArray * stockOutArray;//物料清单Array
@property (nonatomic, strong) UIButton * certainButton;
@end

@implementation YWMaterialNumbleCertainTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.stockOut?@"物料领用确认":@"物料归还确认";
    
    [self.tableView registerClass:[YWMaterialDetailAndCertainHeadTableViewCell class] forCellReuseIdentifier:YWMaterialDetailAndCertainHeadTableViewCellIdentifier];
    [self.tableView registerClass:[YWMaterialInfoTableViewCell class] forCellReuseIdentifier:YWMaterialInfoTableViewCellIdentifier];
    self.tableView.tableFooterView = self.footView;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    if (self.stockOut) {
        self.stockOutArray = self.stockOut.details;
    }else{
        self.stockOutArray = self.returnBack.details;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else{
        return self.stockOutArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        YWMaterialDetailAndCertainHeadTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMaterialDetailAndCertainHeadTableViewCellIdentifier];
        [self configureHeadViewCell:cell atIndexPath:indexPath];
        return cell;
    }else{
        YWMaterialInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWMaterialInfoTableViewCellIdentifier];
        [self configureCell:cell atIndexPath:indexPath];
        return cell;
    }
}

- (void)configureCell:(YWMaterialInfoTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.fd_enforceFrameLayout = NO;
    if (self.stockOut) {
        YWMaterialStockOutDetail * stockOutDetail = self.stockOutArray[indexPath.row];
        cell.stockOutDetail = stockOutDetail;
    }else{
        YWMaterialReturnDetail * returnDetail = self.stockOutArray[indexPath.row];
        cell.returnDetail = returnDetail;
    }
}

- (void)configureHeadViewCell:(YWMaterialDetailAndCertainHeadTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    cell.fd_enforceFrameLayout = NO;
    if (self.stockOut) {
        cell.receipient = self.stockOut;
    }else{
        cell.returnBack = self.returnBack;
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section == 0) {
//        return [tableView fd_heightForCellWithIdentifier:YWMaterialDetailAndCertainHeadTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMaterialDetailAndCertainHeadTableViewCell *cell) {
//            [self configureHeadViewCell:cell atIndexPath:indexPath];
//        }];
//    }else{
//        return [tableView fd_heightForCellWithIdentifier:YWMaterialInfoTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMaterialInfoTableViewCell *cell) {
//            [self configureCell:cell atIndexPath:indexPath];
//        }];
//    }
//}

#pragma mark-------sectionHeaderView------
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWMaterialDetailTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2016;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 25);
    return headerView;
    
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        return self.stockOut?@"物料领用清单":@"物料归还清单";
    }else
    {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 25;
    }else{
        return 0.01;
    }
}

#pragma mark - footView

- (UIView *)footView{
    
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        _footView = footView;
    }
    [_footView addSubview:self.certainButton];
    _footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH*2 + 15 * 2);
    return _footView;
}

- (UIButton *)certainButton{
    if (!_certainButton) {
        UIButton* certainButton = [UIButton buttonWithType:UIButtonTypeSystem];
        certainButton.frame = CGRectMake(10, 15, SCREEN_WIDTH - 10 * 2, kButtonH);
        [certainButton setBackgroundColor:[UIColor customBlueColor]];
        [certainButton setTitle:@"确定" forState:UIControlStateNormal];
        certainButton.titleLabel.font = kBoldTitleFont;
        [certainButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [certainButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateDisabled];
        [certainButton setBackgroundImage:[UIImage imageWithColor:[UIColor customBackgroudColor]] forState:UIControlStateDisabled];
        certainButton.layer.borderColor = [UIColor customBlueColor].CGColor;
        certainButton.clipsToBounds = YES;
        certainButton.layer.cornerRadius = 5.0;
        [certainButton addTarget:self action:@selector(handlecertainButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        _certainButton = certainButton;
        [_footView addSubview:_certainButton];
    }
    return _certainButton;
}

- (void)handlecertainButtonEvent:(UIButton*)sender{
    if (self.scanStockOut) {
        NSString * buildingId = self.scanStockOut[0];
        NSInteger creatorId = [self.scanStockOut[1] integerValue];
        NSInteger stockOutId = [self.scanStockOut[3] integerValue];
        [[YWMaterialManager shareManager] certurnMaterialStockoutWithBuildingId:buildingId CreatorId:creatorId StockOutId:stockOutId WithComplete:^(BOOL success) {
            if (success) {
                
               
                [[YWMaterialManager shareManager] updateMaterialStockOutStatusWithStockOutId:stockOutId];
                 YWMaterialStockOut * stockOut = [[YWMaterialManager shareManager] materialReceipientWithMaterialReceipientId:stockOutId];
                NSDictionary * dic =[[NSDictionary alloc] initWithObjectsAndKeys:stockOut,@"stockOut", nil];
                if (stockOut) {
                    //返回
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPostBackToApplyTableViewNotification object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPostStockOutCertainAfterRefreshRecordViewNoti object:nil userInfo:dic];
                    YWMaterialRecordTableViewController * materailRecord = [[YWMaterialRecordTableViewController alloc] init];
                    materailRecord.stockOut = stockOut;
                    [self.navigationController pushViewController:materailRecord animated:YES];
                }
            }else{
                [YWCommonTool showTextHUDWithContent:@"物料领用失败，请重试！"];
            }
        }];
    }else{
        NSString * buildingId = self.scanReturn[0];
        NSInteger creatorId = [self.scanReturn[1] integerValue];
        NSInteger returnId = [self.scanReturn[3] integerValue];
        [[YWMaterialManager shareManager] certurnMaterialReturnWithBuildingId:buildingId CreatorId:creatorId ReturnId:returnId WithComplete:^(BOOL success) {
            if (success) {
                [[YWMaterialManager shareManager] updateMaterialReturnStatusWithMaterialReturnId:returnId];
                YWMaterialReturn * materialReturn = [[YWMaterialManager shareManager] materialReturnWithMaterialReturnId:returnId];
                 NSDictionary * dic =[[NSDictionary alloc] initWithObjectsAndKeys:materialReturn,@"materialReturn", nil];
                if (materialReturn){
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPostHaveStockOutBackNotification object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:KPostReturnCertainAfterRefreshNotification object:nil userInfo:dic];
                    YWMaterialRecordTableViewController * materailRecord = [[YWMaterialRecordTableViewController alloc] init];
                    materailRecord.returnBack = materialReturn;
                    [self.navigationController pushViewController:materailRecord animated:YES];
                }
            }else{
                [YWCommonTool showTextHUDWithContent:@"物料归还失败，请重试！"];
            }
        }];
    }
}

@end
